//
//  PostsViewController.m
//  ViewPoint
//
//  Created by Demiao Lin on 10/20/08.
//  Copyright 2008 Tsinghua. All rights reserved.
//


#import "PostsViewController.h"
#import "PostViewController.h"
#import "ThreadViewController.h"

#import "NewSMTH.h"

#define INDICATOR_VIEW	999
#define TOOLBAR_VIEW    998
#define UPDATEINTERVAL	120

@implementation PostsViewController

@synthesize postViewController;
@synthesize threadViewController;

@synthesize posts;

@synthesize board;
@synthesize page_num;
@synthesize tableView;

- (id)init{
	if( (self=[super init]) != nil ){
        self.page_num = 0;
		PostViewController *onePostViewController = [[PostViewController alloc] init];
		self.postViewController = onePostViewController;
		[onePostViewController release];
        
        ThreadViewController *oneThreadViewController = [[ThreadViewController alloc] init];
		self.threadViewController = oneThreadViewController;
		[oneThreadViewController release];
	}
	return self;
}

- (id) initWithTitle:(NSString*) title
			   board:(Board*) b {
	if( (self=[self init]) != nil ){
        [self setTitle:title board:b];
	}
	return self;
}

- (void) setTitle:(NSString*) view_title 
			board:(Board*) b{
    if(self.board && b && self.board.bid==b.bid){
        
    }else{
        self.title = view_title;
        self.board = b;
        self.page_num = 0;
		
		lastUpdateTime = CFAbsoluteTimeGetCurrent();
		
        self.posts = nil;
        [self.tableView reloadData];
    }
}

- (void)loadView
{	
    CGRect rect = [[UIScreen mainScreen] applicationFrame];
	UIView *mainView = [[UIView alloc] initWithFrame:rect];
	self.view = mainView;
	[mainView release];
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    rect.size.height = 44.0f;
    
	UITableView *oneTableView = [[UITableView alloc] initWithFrame:rect
                                                             style:UITableViewStylePlain];
	
    UIView *tableHeaderView = [[UIView alloc] initWithFrame:rect];
    UIView *tableFooterView = [[UIView alloc] initWithFrame:rect];
    //tableHeaderView.tag = kHeaderViewTag;
    //tableFooterView.tag = kFooterViewTag;
    oneTableView.tableHeaderView = tableHeaderView;
    oneTableView.tableFooterView = tableFooterView;
    [tableHeaderView release];
    [tableFooterView release];
    
    [oneTableView setEditing:NO animated:YES];
    [oneTableView setAutoresizingMask: (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth) ];
	[oneTableView setDelegate: self];
    [oneTableView setDataSource: self];
	self.tableView = oneTableView;
	[self.view addSubview:oneTableView];
    [oneTableView release];
    
    [self loadToolbar];
    
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
	//[activityIndicator setCenter:CGPointMake(rect.size.width/2, rect.size.height/2)];
    [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
	activityIndicator.tag = INDICATOR_VIEW;
    [self.view addSubview:activityIndicator];
	[activityIndicator release];
    
    //[self setViewsRotation];
}

- (void)viewDidLoad {
	[super viewDidLoad];
	//NSLog(@"posts viewDidLoad");
}

- (void)viewWillAppear:(BOOL)animated {
	//NSLog(@"posts viewWillAppear");
	[super viewWillAppear:animated];
    [self setViewsRotation];
	//[self loadTableView];
	//self.view = nil;
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	//NSLog(@"posts viewDidAppear");
	[self loadTableView];
}

- (void)viewWillDisappear:(BOOL)animated {
	//NSLog(@"posts viewWillDisappear");
}
- (void)viewDidDisappear:(BOOL)animated {
	//NSLog(@"posts viewDidDisappear");
}

-(void) loadTableViewData:(id)object{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	//NSLog(@"posts loadTableViewData 1");
	//NSLog(@"start download, posts length:%d", [self.posts count]);
    
    ArrayAndPageNum *data = [[[[NewSMTH alloc] init] autorelease] getPostsWithBoardName:[self.board bname] page_num:self.page_num];
	if(data!=nil){
        self.posts = data.array;
        self.page_num = data.page_num;
        
        /*
        UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Debug 2"
                                                         message:[NSString stringWithFormat:@"page num:%d", self.page_num]
                                                        delegate:nil
                                               cancelButtonTitle:@"Dismiss"
                                               otherButtonTitles:nil] autorelease];
        [alert show];
        */
        
        //NSLog(@"posts length:%d", [self.posts count]);
        [self.tableView reloadData];
        [self.tableView flashScrollIndicators];
    }
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
	[activityIndicator stopAnimating];
	
	lastUpdateTime = CFAbsoluteTimeGetCurrent();
	
	[pool release];
}

-(void) loadTableView{
	CFAbsoluteTime currentTime = CFAbsoluteTimeGetCurrent(); 
	if(self.posts==nil || [self.posts count]==0 || currentTime-lastUpdateTime>UPDATEINTERVAL){
		//NSLog(@"posts loadTableView");
		UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
		[activityIndicator startAnimating];
		//[self loadTableViewData];
		[self performSelectorInBackground:@selector(loadTableViewData:) withObject:nil];
		//[NSThread detachNewThreadSelector:@selector(loadTableViewData:) toTarget:self withObject:nil];
	}
}


- (UITableViewCell *)tableView:(UITableView *)onetableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if([indexPath row]==0){
		//[self performSelectorInBackground:@selector(loadPreviousPage:) withObject:nil];
	} else if ([indexPath row]==[self.posts count]-1){
		//[self performSelectorInBackground:@selector(loadNextPage:) withObject:nil];
	}
	
	NSString *CellIdentifier = @"PostsCell";
    UITableViewCell *cell = [onetableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        //CGRect cellFrame = CGRectMake(0,0,300,60);
        //cell = [[[UITableViewCell alloc] initWithFrame:cellFrame reuseIdentifier:CellIdentifier] autorelease];
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
        
        CGRect titleLabelRect = CGRectMake(5,0,300,30);
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:titleLabelRect];
        [titleLabel setAutoresizingMask: UIViewAutoresizingFlexibleWidth];
        titleLabel.textAlignment = UITextAlignmentLeft;
        titleLabel.font = [UIFont boldSystemFontOfSize:18];
        //titleLabel.textColor = [UIColor grayColor];
        titleLabel.tag = kTitleTag;
        [cell.contentView addSubview: titleLabel];
        [titleLabel release];
        
        
        CGRect authorLabelRect = CGRectMake(5,30,85,20);
        UILabel *authorLabel = [[UILabel alloc] initWithFrame:authorLabelRect];
        authorLabel.textAlignment = UITextAlignmentLeft;
        authorLabel.font = [UIFont boldSystemFontOfSize:14];
        authorLabel.textColor = [UIColor purpleColor];
        authorLabel.tag = kAuthorTag;
        [cell.contentView addSubview: authorLabel];
        [authorLabel release];
        
        CGRect dateLabelRect = CGRectMake(90,30,190,20);
        UILabel *dateLabel = [[UILabel alloc] initWithFrame:dateLabelRect];
        dateLabel.textAlignment = UITextAlignmentRight;
        dateLabel.font = [UIFont boldSystemFontOfSize:14];
        dateLabel.textColor = [UIColor orangeColor];
        dateLabel.tag = kDateTag;
        [cell.contentView addSubview: dateLabel];
        [dateLabel release];
        
    }
    
    UILabel *title_label = (UILabel*)[cell.contentView viewWithTag:kTitleTag];
    UILabel *author_label = (UILabel*)[cell.contentView viewWithTag:kAuthorTag];
    UILabel *date_label = (UILabel*)[cell.contentView viewWithTag:kDateTag];
    
    Post *post = [self.posts objectAtIndex:[indexPath row]];
    title_label.text = [post title];
    author_label.text = [post user];
    date_label.text = [post date];

    return cell;
}

- (void)loadToolbar {
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
    NSMutableArray *buttons = [[NSMutableArray alloc] initWithCapacity:5];
	
	UIBarButtonItem *flexibleSpaceItem;
    
    /*
	flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil 
                                                                       action:NULL] autorelease];	
	[buttons addObject:flexibleSpaceItem];
	[flexibleSpaceItem release];
	*/
	 
	UIBarButtonItem *item;
	item = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"prePage.png"]
                                             style:UIBarButtonItemStylePlain 
                                            target:self 
                                            action:@selector(loadPreviousPage:)] autorelease];
	[buttons addObject:item];
	
    flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil 
                                                                       action:NULL] autorelease];	
	[buttons addObject:flexibleSpaceItem];
    
	/*
	UILabel *pageLabel = [[UILabel alloc] init];
	pageLabel.textAlignment = UITextAlignmentLeft;
	pageLabel.font = [UIFont boldSystemFontOfSize:18];
	pageLabel.text = [NSString stringWithFormat:@"[%d]", self.page_num];
	
	[buttons addObject:pageLabel];
	[pageLabel release];
	*/
    
	/*
	item = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"thread.png"]
                                             style:UIBarButtonItemStylePlain
                                            target:self
                                            action:@selector(loadNextPage:)] autorelease];
	[buttons addObject:item];
	
	 
    flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil 
                                                                       action:NULL] autorelease];	
	[buttons addObject:flexibleSpaceItem];
    */
    
    item = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nextPage.png"]
                                             style:UIBarButtonItemStylePlain 
                                            target:self 
                                            action:@selector(loadNextPage:)] autorelease];
	[buttons addObject:item];
	
	
	/*
	flexibleSpaceItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                       target:nil 
                                                                       action:NULL] autorelease];	
	[buttons addObject:flexibleSpaceItem];
	*/
	
    CGRect rect = [[UIScreen mainScreen] applicationFrame];
	UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:rect];
	//toolbar.barStyle = UIBarStyleBlackOpaque;
    toolbar.barStyle = UIBarStyleBlackTranslucent;
	[toolbar setItems:buttons animated:YES];
    [buttons release];
    toolbar.tag = TOOLBAR_VIEW;
	//[toolbar sizeToFit];
    
	//self.navigationItem.titleView = toolbar;
    [self.view setUserInteractionEnabled:YES];
	[self.view addSubview:toolbar];
    [toolbar release];
	
	[pool release];
}

-(void) loadPreviousPage:(id)sender{
	self.page_num -= 1;
	lastUpdateTime = 0;
    [self loadTableView];
}

-(void) loadNextPage:(id)sender{
	self.page_num += 1;
	lastUpdateTime = 0;
    [self loadTableView];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if(self.posts){
        return [self.posts count];
    }else{
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 51;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Post *post = [self.posts objectAtIndex:[indexPath row]];
    [postViewController setPostViewWithTitle:[post title] board:self.board post_id:[post pid] post_type:@"no"];
    [[self navigationController] pushViewController:postViewController animated:YES];
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    Post *post = [self.posts objectAtIndex:[indexPath row]];
    
    /*
    [postViewController setPostViewWithTitle:[post title] board:self.board post_id:[post tid] post_type:@"no"];
    [[self navigationController] pushViewController:postViewController animated:YES];
    //[postViewController hideToolbarAndNavBar];
    */
    
    [threadViewController setThreadViewWithTitle:[post title] board:self.board thread_id:[post tid] post_id:[post tid]];
	[[self navigationController] pushViewController:self.threadViewController animated:YES];
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void) willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation) fromOrientation duration:(NSTimeInterval) duration{
    [self setViewsRotation];
}

- (void) setViewsRotation {
    UIToolbar *toolbar = (UIToolbar*)[self.view viewWithTag:TOOLBAR_VIEW];
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
    
    UIInterfaceOrientation orientation = self.interfaceOrientation;
    if(orientation==UIInterfaceOrientationLandscapeLeft || orientation==UIInterfaceOrientationLandscapeRight){
        [tableView setFrame:CGRectMake(0.0f, 0.0f, 480.0f, 300.0f)];
        [tableView.tableHeaderView setFrame:CGRectMake(0.0f, 0.0f, 480.0f, 32.0f)];
		[toolbar setFrame:CGRectMake(0.0f, 300.0f-44.0f, 480.0f, 44.0f)];
        [activityIndicator setCenter:CGPointMake(240, 140)];
	}else{
		[tableView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)];
        [tableView.tableHeaderView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
        [toolbar setFrame:CGRectMake(0.0f, 460.0f-44.0f, 320.0f, 44.0f)];
        [activityIndicator setCenter:CGPointMake(160, 220)];
	}
	[self.view bringSubviewToFront:toolbar];
	[self.view bringSubviewToFront:activityIndicator];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
	[board release];
	[posts release];
	[postViewController release];
    [threadViewController release];
	[tableView release];
    [super dealloc];
}
@end

